package com.itheima.controller;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/addServlet")
public class AddServlet extends HttpServlet {

    private BrandService brandService = new BrandService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置汉字编码
        request.setCharacterEncoding("utf-8");
        //获取表单所有的数据
        Map<String, String[]> parameterMap = request.getParameterMap();

        //封装Brand对象
        Brand brand = new Brand();
        //调用BeanUtils的工具类，复制属性。需要导入common-beanutis的jar包
        try {
            //将Map对象中同名的键，复制给brand中同名的属性
            BeanUtils.populate(brand, parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //调用业务层添加
        brandService.add(brand);
        //重定向到index.jsp
        response.sendRedirect("index.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
